import importlib
import pkgutil
from fastapi import APIRouter
from pathlib import Path


def auto_register_routes(app, package_path: str, prefix: str = ""):
    """支持前缀的自动注册"""
    package_dir = Path(package_path).resolve()
    package_name = "app.api." + package_dir.name

    base_router = APIRouter(prefix=prefix)  # 新增前缀支持

    for _, module_name, _ in pkgutil.walk_packages([str(package_dir)], prefix=package_name + "."):
        module = importlib.import_module(module_name)
        if hasattr(module, 'router'):
            base_router.include_router(module.router)  # 嵌套到基础路由

    app.include_router(base_router)  # 统一注册